package com.jztchat.webSocket.service.Impl;

import com.corundumstudio.socketio.SocketIOServer;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jztchat.dataobject.MessageInfo;
import com.jztchat.entity.ChatRecord;
import com.jztchat.entity.ClientInfo;
import com.jztchat.redis.RedisKeyConstent;
import com.jztchat.repository.ChatRecordRepository;
import com.jztchat.repository.ClientInfoRepository;
import com.jztchat.webSocket.service.SocketConnectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by zzy on 2018/1/18.
 */
@Service
public class SocketConnectServiceImpl implements SocketConnectService {


    private final static Logger log= LoggerFactory.getLogger(SocketConnectServiceImpl.class);

    /**
     *讲正在连接的用户信息存入redis
     * @param clientInfo
     */

    private RuntimeSchema<ClientInfo> schema = RuntimeSchema.createFrom(ClientInfo.class);


    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ChatRecordRepository chatRecordRepository;
    @Autowired
    private ClientInfoRepository clientInfoRepository;

    @Override
    public void saveClientInfoToRedis(ClientInfo clientInfo) {
        try {
            //序列化
            String key = RedisKeyConstent.CHAT_USER_LOGIN_INFO + clientInfo.getClientid();
            //byte[] bytes= ProtobufIOUtil.toByteArray(clientInfo,schema,LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
            Gson gson = new Gson();
            String json = gson.toJson(clientInfo);
            stringRedisTemplate.opsForValue().set(key, json,30*60, TimeUnit.SECONDS);
        }catch (Exception e){
            log.error("将客户上线信息存入redis"+e.getMessage(),e);
        }
    }

    @Override
    public ClientInfo getClientInfoToRedis(String clientId) {
        ClientInfo result=null;
        try {
            String key="chat:"+clientId;
            Gson gson = new Gson();
            String json=stringRedisTemplate.opsForValue().get(key);
            if(json!=null){
                result=gson.fromJson(json,new TypeToken<ClientInfo>(){}.getType());
            }
        }catch (Exception e){
            log.error("将客户上线信息从redis取出"+e.getMessage(),e);

        }
        return result;
    }

    @Override
    public ChatRecord getChatRecordFormRids(String clientId) {
        ChatRecord chatRecord=null;
        try {
            String key=RedisKeyConstent.CHAT_RECORD_FOR_USER+clientId;
            String recordStr=stringRedisTemplate.opsForValue().get(key);
            Gson gson = new Gson();
            if(recordStr!=null){
                chatRecord=gson.fromJson(recordStr,new TypeToken<ChatRecord>(){}.getType());
            }
        }catch (Exception e){
            return null;
        }
        return chatRecord;
    }

    @Override
    public void setChatRecordToRids(ChatRecord chatRecord) {
        try{
            Gson gson = new Gson();
            String json = gson.toJson(chatRecord);
            String key= RedisKeyConstent.CHAT_RECORD_FOR_USER+chatRecord.getTargetUser();
            stringRedisTemplate.opsForValue().set(key, json,30*60, TimeUnit.SECONDS);
        }catch (Exception e){
            log.error("存入未接收到的信息到redis"+e.getMessage(),e);

        }
    }

    @Override
    public void sendTheMessageBefore(ChatRecord chatRecord, SocketIOServer server) {
        //从缓存中获取，登陆后
        String key= RedisKeyConstent.CHAT_USER_LOGIN_INFO+chatRecord.getTargetUser();
        ClientInfo clientInfo=getClientInfoToRedis(key);
        if(clientInfo==null){
            clientInfo = clientInfoRepository.findByClientid(chatRecord.getTargetUser());
        }
        if(clientInfo==null||chatRecord==null){
            return;
        }
        MessageInfo sendData=MessageInfo.getSendData(chatRecord);
        Long a=clientInfo.getMostsignbits();
        Long b=clientInfo.getLeastsignbits();
        if(a!=null&&b!=null){
            UUID uuid = new UUID(a, b);
            server.getClient(uuid).sendEvent("messageevent", sendData);
            // client.sendEvent("messageevent", sendData);
        }
        //讲消息从redis删除，并设置数据库为已发送
        stringRedisTemplate.opsForValue().getOperations().delete(key);
        chatRecord.setIsSend(1);
        chatRecordRepository.save(chatRecord);
    }
}
